<template>
  <div class="page-detail">
    <base-breadcrumb>
      <a-row :gutter="20" class="page-height">
        <a-col
          span="6"
          class="goods-search-left"
        >
          <a-card class="page-height-tree">
            <!-- <title-name title="物资目录" /> -->
            <a-input-search
              style="margin-bottom: 8px"
              @change="onChange"
            />

            <a-tree
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :tree-data="treeData"
              :selected-keys="selectedKeys"
              :load-data="getTree"
              @select="onSelect"
              @expand="onExpand"
            >
              <template
                slot="title"
                slot-scope="{ title }"
              >
                <span v-if="title.indexOf(searchValue) > -1">
                  {{ title.substr(0, title.indexOf(searchValue)) }}
                  <span style="color: #f50">{{ searchValue }}</span>
                  {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
                </span>
                <span v-else>{{ title }}</span>
              </template>
            </a-tree>
          </a-card>
        </a-col>
        <a-col span="18" class="page-height-list-wrapper">
          <searchData
            ref="searchData"
            :search-data="searchArr"
            @search="search"
            @reset="
              catalogCode = null
              search
            "
          />
          <a-card class="page-height-list">
            <list-table
              ref="table"
              :export-config="{ use: true, select: '导出选中', all: '导出全部' }"
              :columns="columns"
              :request="loadData"
              row-key="code"
            >
              <div
                slot="operation"
                slot-scope="text, record, index"
                class="pub-table-list-action"
              >
                <span v-btn-permission="'mm_030_loo_01'" @click="$router.push({path: 'search/detail',query: { row: record }})">查看</span>
                <span
                  v-btn-permission="'mm_030_edi_02'"
                  @click="
                    visible = true
                    editForm.unit = record.unit
                    editForm.id = record.id
                  "
                >编辑单位</span>
              </div>
            </list-table>
          </a-card>
        </a-col>
      </a-row>
    </base-breadcrumb>
    <a-modal
      :visible="visible"
      title="编辑单位"
      :confirm-loading="modalLoading"
      @ok="editUnit"
      @cancel="visible = false"
    >
      <div class="page-detail">
        <a-form-model
          ref="editForm"
          :model="editForm"
          :rules="editRule"
        >
          <a-row>
            <a-col span="24">
              <a-form-model-item
                label="计量单位"
                prop="unit"
              >
                <BaseInput v-model="editForm.unit" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-modal>
  </div>
</template>
<script>
import { findListAddByMain, findCatalogByTree, editByMain } from '@/api/material/goods/goods'

export default {
    name: 'a' + Date.now(),
    data: function () {
        return {
            loading: false,
            modalLoading: false,
            visible: false,
            queryParam: {},
            editForm: {
                unit: ''
            },
            editRule: {
                unit: { required: true, message: '云筑单位不能为空', trigger: 'blur' }
            },
            searchArr: [
                {
                    name: '物料名称',
                    value: 'name',
                    type: 'input'
                },
                {
                    name: '物料编码',
                    value: 'code',
                    type: 'input'
                },
                {
                    name: '物资目录名称',
                    value: 'catalogName',
                    type: 'input'
                },
                {
                    name: '物资目录编码',
                    value: 'catalogCode',
                    type: 'input'
                },
                {
                    name: '规格型号',
                    value: 'specificationModel',
                    type: 'input'
                },
                {
                    name: '状态',
                    value: 'commonStatus',
                    type: 'select',
                    data: [
                        { value: '0', label: '无效' },
                        { value: '1', label: '有效' },
                        { value: '-999', label: '已删除' }
                    ]
                }
            ],
            columns: [
                {
                    title: '序号',
                    width: 80,
                    dataIndex: 'index',
                    customRender() {
                        return arguments[2] + 1
                    }
                },
                {
                    title: '物料名称',
                    dataIndex: 'name',
                    width: 100
                },
                {
                    title: '物料编码',
                    dataIndex: 'code',
                    width: 130
                },
                {
                    title: '物资目录名称',
                    dataIndex: 'catalogName',
                    width: 130
                },
                {
                    title: '物资目录编码',
                    dataIndex: 'catalogCode',
                    width: 130
                },
                {
                    title: '规格型号',
                    dataIndex: 'specificationModel'
                },
                {
                    title: '计量单位',
                    dataIndex: 'unit',
                    width: 100
                },
                {
                    title: '云筑单位',
                    dataIndex: 'newUnit',
                    width: 100
                },
                {
                    title: '状态',
                    dataIndex: 'commonStatusStr',
                    width: 80
                },
                {
                    title: '操作',
                    dataIndex: 'operation',
                    width: 160,
                    scopedSlots: { customRender: 'operation' }
                }
            ],
            treeData: [],
            catalogCode: null,
            loadData: (params) => {
                let searchData = Object.assign(params, this.queryParam)
                if (searchData.catalogCode) {
                    this.selectedKeys = []
                }
                if (this.selectedKeys.length) {
                    searchData.catalogCode = this.catalogCode
                }
                return findListAddByMain(searchData)
            },
            selectedKeys: [],
            replaceFields: {
                children: 'children',
                title: 'mateClassName',
                key: 'mateClassSysNo'
            },

            expandedKeys: [],
            searchValue: '',
            autoExpandParent: true,
            dataList: []
        }
    },
    mounted: function () {
        this.getTree()
    },
    methods: {
        onExpand(expandedKeys) {
            this.expandedKeys = expandedKeys
            this.autoExpandParent = false
        },
        onChange(e) {
            const value = e.target.value
            const expandedKeys = this.dataList
                .map((item) => {
                    if (item.title.indexOf(value) > -1) {
                        return this.getParentKey(item.key, this.treeData)
                    }
                    return null
                })
                .filter((item, i, self) => item && self.indexOf(item) === i)
            Object.assign(this, {
                expandedKeys,
                searchValue: value,
                autoExpandParent: true
            })
            console.log(expandedKeys)
            console.log(this.searchValue)
        },
        generateList(data) {
            for (let i = 0; i < data.length; i++) {
                const node = data[i]
                const key = node.key
                const title = node.title
                // this.dataList.push({ key, title: key })
                this.dataList.push({ key, title })
                if (node.children) {
                    this.generateList(node.children)
                }
            }
        },
        getParentKey(key, tree) {
            let parentKey
            for (let i = 0; i < tree.length; i++) {
                const node = tree[i]
                if (node.children) {
                    if (node.children.some((item) => item.key === key)) {
                        parentKey = node.key
                    } else if (this.getParentKey(key, node.children)) {
                        parentKey = this.getParentKey(key, node.children)
                    }
                }
            }
            return parentKey
        },
        async editUnit(e) {
            this.$refs.editForm.validate(async (valid) => {
                if (valid) {
                    this.modalLoading = true
                    let res = await editByMain(this.editForm)
                    this.modalLoading = false
                    if (res.code === this.SUCCESS_CODE) {
                        this.$noticeSuccess('修改成功')
                        this.visible = false
                        this.search()
                    }
                } else {
                    this.$noticeWarning('请填写云筑单位')
                }
            })
        },
        search(val) {
            this.queryParam = val
            this.$refs.table.getData(null, true)
        },
        async getTree(treeNode) {
            return new Promise(async (resolve) => {
                let sysNo = 0
                if (treeNode) {
                    if (treeNode.dataRef.children) {
                        resolve()
                        return
                    }
                    sysNo = treeNode.eventKey
                }
                this.loading = true
                let res = await findCatalogByTree({ sysNo })
                this.loading = false
                if (res.code === this.SUCCESS_CODE) {
                    res.data = res.data.map((v) => {
                        v.scopedSlots = { title: 'title' }
                        v.key = v[this.replaceFields.key]
                        v.title = v[this.replaceFields.title]
                        return v
                    })
                    if (sysNo === 0) {
                        this.treeData = res.data
                    } else {
                        treeNode.dataRef.children = res.data
                        this.treeData = [...this.treeData]
                    }
                    this.generateList(this.treeData)
                    console.log(this.treeData)
                    console.log(this.dataList)
                }
                resolve()
            })
        },
        onSelect: function (selectedKeys, info) {
            this.selectedKeys = selectedKeys
            if (selectedKeys.length) {
                this.catalogCode = info.selectedNodes[0].data.props.mateClassCode
            } else {
                this.catalogCode = null
            }
            this.$refs.searchData.resetFormItem('catalogCode')
            this.$refs.table.getData(null, true)
        }
    }
}
</script>
<style scoped>
.goods-search-left .ant-tree {
    overflow: auto;
}
</style>
